import { getCategorys } from "@/api/resource";

const resource = {
  state: {
    categoryList: [],
    categoryRootMenu: [
      {
        // id: "NONFERROUS",
        id: 1,
        categoryName: "有色",
        children: []
      },
      {
        // id: "FERROUS",
        id: 2,
        categoryName: "黑色",
        children: []
      },
      {
        // id: "CHEMICAL",
        id: 3,
        categoryName: "化工",
        children: []
      },
      {
        // id: "FARM",
        id: 4,
        categoryName: "农产品",
        children: []
      },
      {
        // id: "ENERGY",
        id: 5,
        categoryName: "能源",
        children: []
      },
      {
        // id: "OTHER",
        id: 6,
        categoryName: "其他",
        children: []
      }
    ]
  },
  mutations: {
    SET_CATEGORYLIST: (state, data) => {
      state.categoryList = data;
    }
  },
  actions: {
    // 获取所有品种
    getCategoryList({ state, commit }) {
      return new Promise(resolve => {
        if (sessionStorage.getItem("category")) {
          let data = sessionStorage.getItem("category");
          commit("SET_CATEGORYLIST", JSON.parse(data));
          resolve(JSON.parse(data));
        } else {
          getCategorys().then(res => {
            let data = res.concat(state.categoryRootMenu);
            sessionStorage.setItem("category", JSON.stringify(data));
            commit("SET_CATEGORYLIST", data);
            resolve(data);
          });
        }
      });
    }
  }
};

export default resource;
